<template>
    <view>
		
		<!-- 小程序顶部样式 -->
		<cu-custom bgColor="bg-gradual-orange" :isBack="false">
			<block slot="left">
				<text @tap="toPage()" class="cuIcon-peoplefill" style="font-size: 40rpx;"></text>
			</block>
			<block slot="content">首页</block>
		</cu-custom>
		
		<view v-if="userInfo.auditStatus == 'CERTIFIED'" class="cu-modal bottom-modal" :class="modalName=='bottomModal'?'show':''">
			<view class="cu-dialog">
				<view class="cu-bar bg-white">
					<button class="action text-green setting-btn" open-type="openSetting" 
					bindopensetting="toSetting">确定</button>
				</view>
				<view class="padding-xl">
					您未授权获取您的位置信息，小程序将无法正常运行，请您点击确定选择位置信息
				</view>
			</view>
		</view>
		
		
		<!-- token过期获取token时显示的内容 -->
		<view :class="token ? 'display' : ''" style="height:100vh;position:fixed;top:70px;background-color:#F2F2F2;width:100%;z-index:100;">
			<view class="flex justify-center flex-direction align-center" style="height: 90vh;">
				<text style="font-size: 50rpx;color: #8F8F94;font-weight: bold;margin-bottom: 50rpx;">
					正在加载
				</text>
			</view>
		</view>
		
		<view v-if="userInfo.auditStatus != 'CERTIFIED'" class="bg-white">
			<view v-if="!userInfo.auditStatus" class="flex justify-center flex-direction align-center" style="height: 90vh;">
				<text style="font-size: 50rpx;color: #8F8F94;font-weight: bold;margin-bottom: 50rpx;">
					您还未认证
				</text>
				<button @tap="attestation" type="default" style="border: solid 3upx #0081ff; background-color: white;color: #0081ff;width: 300upx;border-radius: 0upx;font-size: 30upx;border-radius: 10rpx;">立即认证</button>
			</view>
			<view v-else-if="userInfo.auditStatus == 'CERTIFICATING'" class="flex justify-center flex-direction align-center" style="height: 90vh;">
				<text style="font-size: 50rpx;color: #8F8F94;font-weight: bold;margin-bottom: 50rpx;">
					认证中
				</text>
			</view>
		</view>
		
		<!-- 认证成功，获取数据 -->
		<view v-else-if="userInfo.auditStatus == 'CERTIFIED'">
			
			<!-- token过期获取token时显示的内容 -->
			<view class="flex flex-column justify-center align-center" v-if="orders.length == 0" style="height: 60vh;">
				<view class="text-xxl text-gray">
					暂无订单哦
				</view>
			</view>
			
			<!-- 悬浮来新订单通知栏 -->
			<view v-if="newOrder && newOrder.location" @tap="newOrderDetail" style="position: fixed;top: 117rpx;width: 100%;z-index: 100;">
				<view class="bg-orange flex flex-row justify-center align-center">
					<text class="lg text-white cuIcon-notificationfill" style="font-size: 27rpx;margin-right: 5rpx;"></text>
					<text class="text-white" style="font-size: 27rpx;line-height: 50rpx;height: 50rpx;">
						有来自{{ newOrder.location.address }}的新订单啦，快来抢单吧！！！
					</text>
					<view style="position: absolute; right: 10rpx;">
						<text class="lg text-white cuIcon-right" style="font-size: 27rpx"></text>
					</view>
				</view>
			</view>
			<!-- 悬浮回到顶部按钮 -->
			<view @tap="toTop" style="position: fixed;bottom: 50rpx;right: 50rpx;">
				<view class="bg-orange flex justify-center align-center" style="width: 100rpx;height: 100rpx;border-radius: 50%;">
					<text class="lg text-white cuIcon-top" style="font-size: 40rpx;"></text>
				</view>
			</view>
			<view v-for="(item, index) in orders" :key="item.id">
				<view class="cu-card">
						<view class="cu-item shadow cu-card-custom" :data-id="item" @tap="orderDetail">
							<view class="">
								维修类型：
								<text>
									{{ item.serviceName }}
								</text>
							</view>
							<view class="flex align-center margin-sm">
								<image :src="handleImg(item.scenePhoto)"
								 mode="top" style="width: 100%;height: 300rpx;"></image>
							</view>
							<view class="flex align-center">
								<view class="cu-round margin-xs" style="background-color: #1AAD19;"></view>
								<text>
									{{ item.location.address }}
								</text>
							</view>
							<view class="flex align-center">
								<view class="cu-round margin-xs" style="background-color: #FF3333;"></view>
								<text>距您{{ item.distance }}千米</text>
							</view>
							<view class="flex margin-sm" style="margin-bottom: 0rpx;">
								<view>
									备注：
								</view>
								<text class="text-cut" style="width: 80%;">
									{{ item.remark }}
								</text>
							</view>
							<view class="flex justify-end align-center padding-top-sm">
								维修费用：
								<text class="text-price text-red text-xxl">
									{{ item.realAmount }}
								</text>
							</view>
						</view>
					</view>
				</view>
			</view>
    </view>
</template>

<script>
	
	import util from '../../common/util.js'
	import mqtt from '../../common/mqtt.js'
	
    import {
        mapState,
    	mapMutations
    } from 'vuex'
	
    export default {
		components:{
		},
		data() {
			return {
				//显示获取位置信息的模态窗
				modalName: '',
				orders: [],
				baseImg: '',
				newOrder: {}
			}
		},
        computed: {
			token: () => uni.getStorageSync('token'),
			userInfo: () => uni.getStorageSync('userInfo'),
		},
        onLoad() {		
			//初始化mqtt
			this.initMqtt()
			//初始化图片地址
			this.baseImg = this.$api.baseImg
        },
		onShow() {
			//onshow 如果用户当前状态不是已审核，则请求服务器查看当前用户是否审核成功
			//审核成功 获取有效订单
			if(this.userInfo ){
				if(this.userInfo.auditStatus != 'CERTIFIED'){
					//如果用户未审核成功，则查询用户状态
					this.getUserAuditStatus()
				}else{
					//用户审核成功，直接获取有效订单
					this.effictiveOrders()
				}
			}
			//处理没有获取位置权限的用户
			let that = this
			uni.getSetting({
			   success(res) {
				  if (res.authSetting['scope.userLocation'] === undefined) {
				    console.log('未授权位置信息')
				  	that.modalName = 'bottomModal'
				  }
				  else if (res.authSetting['scope.userLocation']) {
				    that.modalName = ''
				  }
				  
			   }
			})
		},
		methods:{
			//滚动到页面顶部
			toTop(){
				uni.pageScrollTo({
					scrollTop: 0,
					duration: 300
				});
			},
			//处理图片
			handleImg(e){
				return this.baseImg + e.split(',')[0]
			},
			//获取有效订单
			effictiveOrders(){
				//先获取位置，再请求接口，接口直接计算距离
				let that = this
				uni.getLocation({
					type: 'wgs84',
					success: function (res) {
						that.modalName = ''
						that.$api.effictiveOrders({location: JSON.stringify(res)}).then((res)=>{
							that.orders = res.data.data
						}).catch((err)=>{
							console.log('request fail', err);
						})
					},
					fail(err) {
						that.modalName = 'bottomModal'
					}
				});
			},
			//获取当前用户审核状态
			async getUserAuditStatus(){
				let audit = await this.$api.getUserAuditStatus()
				if(audit.data.data == 'CERTIFIED'){
					this.userInfo.auditStatus = 'CERTIFIED'
					uni.setStorageSync('userInfo', this.userInfo)
					uni.reLaunch({
						url: './main'
					})
				}
			},
			//订单详情页面
			orderDetail(e){
				uni.setStorageSync('orderDatil', e.currentTarget.dataset.id)
				uni.navigateTo({
					url: '../orderDetail/orderDetail'
				})
			},
			newOrderDetail(){
				uni.setStorageSync('orderDatil', this.newOrder)
				uni.navigateTo({
					url: '../orderDetail/orderDetail'
				})
			},
			hideModal(e) {
				this.modalName = null
			},
			toPage(){
				uni.navigateTo({
					url: '../user/user'
				})
			},
			//认证
			attestation(){
				if(!this.userInfo.nickName){
					uni.navigateTo({
						url: '../user/user'
					})
				}else{
					uni.navigateTo({
						url: '../attestation/attestation'
					})
				}
			},
			playNewOrder(){
				const innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.autoplay = true;
				innerAudioContext.src = this.$util.getDicByKey("newOrdersVoice")
				innerAudioContext.onPlay(() => {
				  console.log('开始播放');
				});
				innerAudioContext.onError((res) => {
				  console.log(res.errMsg);
				  console.log(res.errCode);
				});
			},
			initMqtt(){
				let that = this
				// 连接选项
				const options = {
				  connectTimeout: 4000, // 超时时间
				  // 认证信息 按自己需求填写
				  clientId: 'miniapp_clientid',
				  username: 'username',
				  password: 'password',
				  port: 443
				}
				const client = mqtt.connect('wxs://127.0.0.1/wss', options)
				client.on('reconnect', (error) => {
				  console.log('正在重连:', error)
				})
				client.on('error', (error) => {
				  console.log('连接失败:', error)
				})
				client.on('connect', (e) => {
				  console.log('成功连接服务器')
					//订阅一个主题
				  client.subscribe('topic', { qos: 2 }, function (err) {
					if (!err) {
						setInterval(function(){
							if(that.userInfo && that.userInfo.id){
								uni.getLocation({
									type: 'wgs84',
									success: function (res) {
										res.userId = that.userInfo.id
										client.publish('location', JSON.stringify(res))
										console.log("发送位置成功")
									}
								});
							}
						}, 60 * 1000)
					}
						 
				  })
				})
				//监听mq的返回
				client.on('message', function (topic, message, packet) {
				  // message is Buffer
				  let order = JSON.parse(packet.payload.toString())
				  let flag = that.orders.some(e => e.id == order.id)
				  if(!flag){
					  that.orders.unshift(order)
					  //播放新订单声音
					  that.playNewOrder()
					  that.newOrder = order
					  setTimeout(function(){
						  that.newOrder = {}
					  }, 4000)
				  }
				  // client.end()
				})
			}
		}
    }
</script>

<style>
	.display{
		display: none;
	}
	
	.setting-btn{
		background-color: unset;
		border: unset;
		position: unset;
	}
	
	.cu-card-custom{
		height: 650rpx;
		padding: 20rpx;
	}
	.cu-round{
		height: 30rpx;width: 30rpx;border-radius: 50%;
	}
</style>
